import { useReactive } from "ahooks";
import { useEffect } from "react";

const useRemoteInfo = (isReload = false) => {
    const state = useReactive({
        loading: false,
        remoteOrganizationInfo: [],
    });

    const loadRemoteOrganizationInfo = async (isReload) => {
        if (isReload === false) {
            let cacheServers = nodeCache.get(window.organizationUuid + "-remoteOrganizationInfo");
            if (cacheServers && cacheServers.length > 0) return (state.remoteOrganizationInfo = cacheServers);
        }
        state.loading = true;
        const { loginInfo } = remote.getGlobal("personInfo");
        let { statusCode, message, result } = await httpRequest({
            object: "public-user-auth-center",
            serviceUrl: loginInfo.authCenterUrl,
            serviceName: "/api/v1/organization/getBaseInfo",
            params: { uuid: window.organizationUuid },
        });
        if (statusCode === 0) {
            state.remoteOrganizationInfo = result || {};
            nodeCache.set(window.organizationUuid + "-remoteOrganizationInfo", result, 2 * 60 * 60); // 缓存两个小时
        }
        state.loading = false;
    };

    useEffect(() => {
        loadRemoteOrganizationInfo(isReload);
    }, []);

    return { ...state, loadRemoteOrganizationInfo };
};

export default useRemoteInfo;
